package com.yex.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yex.common.utils.DateUtil;
import com.yex.common.utils.PageUtils;
import com.yex.dao.QuestionDao;
import com.yex.entity.QuestionEntity;
import com.yex.service.LocaleMessageSourceService;
import com.yex.service.QuestionService;
import com.yex.utils.JsonResultVo;
import com.yex.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service("questionService")
public class QuestionServiceImpl extends ServiceImpl<QuestionDao, QuestionEntity> implements QuestionService {
    @Autowired
    private LocaleMessageSourceService message;

    @Override
    public PageUtils queryPage(Map<String, Object> params, String filter) {
        Page<Map<String, Object>> page = new Query<Map<String, Object>>(params).getPage();
        List<Map<String, Object>> questionEntityList = baseMapper.selectPageFilter(page, filter);
        page.setRecords(questionEntityList);
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public JsonResultVo insertQuestion(Integer userId, String content, String ip) {
        QuestionEntity questionEntity = new QuestionEntity();
        questionEntity.setUserId(userId);
        questionEntity.setContent(content);
        questionEntity.setCreateTime(new Date());
        questionEntity.setStatus(1);
        questionEntity.setIp(ip);
        Integer result = baseMapper.insert(questionEntity);
        return result > 0 ? new JsonResultVo(message.getMessage("success")) : new JsonResultVo(message.getMessage("fail"), -1);
    }

    @Override
    public JsonResultVo selectQuestionList(Integer userId) {

        List<QuestionEntity> questionList = baseMapper.selectQuestionList(userId);
        List<Map<String, Object>> mapList = new ArrayList<>();

        for (QuestionEntity questionEntity : questionList) {
            Map<String, Object> map = new HashMap<>(5);
            map.put("id", questionEntity.getId());
            map.put("content", questionEntity.getContent());
            map.put("replyContent", questionEntity.getReplyContent());
            map.put("createTime", DateUtil.format(DateUtil.ZH_CN_DATE_TIME_STAMP, questionEntity.getCreateTime()));
            map.put("replyTime", DateUtil.format(DateUtil.ZH_CN_DATE_TIME_STAMP, questionEntity.getReplyTime()));
            mapList.add(map);
        }

        return new JsonResultVo(message.getMessage("success"), mapList, 0);
    }
}
